package top.hidoctor.auscultation.utils;

import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class GitImageOriginWidthAndHeight {
    static Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };
    static ExecutorService mPicFixThreadPool = Executors.newCachedThreadPool();

    public static void getPicSize(final String url, final OnPicListener listener) {

        mPicFixThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection;
                try {
                    connection = (HttpURLConnection) new URL(url).openConnection();
                    InputStream inputStream = connection.getInputStream();
                    final int[] imageSize = getImageSize(inputStream);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onImageSize(imageSize[0], imageSize[1]);
                        }
                    });
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static int[] getImageSize(InputStream is) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(is, null, options);
        int[] size = new int[2];
        size[0] = options.outWidth;
        size[1] = options.outHeight;
        Log.i("TAG", "--------------------width = " + size[0] + ",height = " + size[1] + "--------------------");
        return size;
    }

    public interface OnPicListener {
        void onImageSize(int width, int height);
    }
}

